package net.ojbk.timeAxis.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;

import net.ojbk.timeAxis.service.LoginAndRegisterServlice;

/**
 * Servlet implementation class LoginAndRegisterServlet
 */
@WebServlet("/LoginAndRegisterServlet")
public class LoginAndRegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginAndRegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("------------------");
		response.setContentType("text/html;charset=utf-8");
	    response.setCharacterEncoding("utf-8");
	    request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
	    
	    String type = request.getParameter("type");
	    String userId = request.getParameter("userId");
	    String userPW = request.getParameter("userPW");
	    System.out.println(userId);
	    System.out.println(userPW);
		HttpSession session=request.getSession();
	    Map<String,Object>map=new HashMap<String,Object>(); // 够着 json
	    
	    LoginAndRegisterServlice service = new LoginAndRegisterServlice();
	    if (type.equals("login")) { // 登录
	    	int flag = service.login(userId, userPW);
	    	if (flag == 1) {
	    		map.put("status", true);
	    		session.setAttribute("login", true);
	    		session.setAttribute("userId", userId);
	    	} else
	    		map.put("status", false);
	    	
	    } else if (type.equals("register")) { // 注册
	    	int flag = service.register(userId, userPW);
	    	if (flag == 1) {
	    		map.put("status", true);
	    	} else
	    		map.put("status", false);
	    } else {
	    	map.put("status", false);
	    }
	    
		// 写出到 json
		JSONObject json=new JSONObject(map); // 转化为 json对象
		out.write(json.toString());
		out.flush();
		System.out.println(json.toString());
	    
	}

}
